<?
	session_start(); if (!$_SESSION['logged']) {header("Location: index.php"); die();}

	$response_img_dir = "/user/images/response/";

	include_once ('../core/class.upload.php');
	include_once ('../core/adds.php');

//	echo "<pre>"; print_r ($_POST); echo "</pre>";

	if (!empty($_POST['item_id_order'])) {
		include ('../user/counter_rsp.php');
		$resp_ids=explode(",",$resp_ids_string);

		// этот блок нужен для добавления новых отзывов
		foreach ($_POST as $k => $v) {
			$tmp = preg_match("/response_([0-9]+)_name/",$k,$matches);
			if (($tmp > 0)&&(!in_array($matches[1],$resp_ids))) {
				$resp_ids[] = $matches[1];
				if (empty($_POST['response_'.$matches[1].'_name'])) $_POST['response_'.$matches[1].'_name'] = "имя";
			}
			$resp_ids = array_unique($resp_ids);
		}

		$tmp = array_map("rem_item_order_trash",explode("&",$_POST['item_id_order']));
		$resp_order = array_combine(array_values($tmp),array_keys($tmp));
		$field_kind = array('name','contact','text');

		$resp2delete = array();
		$out_file = '';
		$new_pos = '1000'; // для новых элементов берем фонарное значение позиции, так чтоб было последним
		include ('../user/response.php');

		foreach ($resp_ids as $r_id) {
			// если не пришло имя - элемент считаем удаленным
			if (empty($_POST['response_'.$r_id.'_name'])) {
				$resp2delete[] = $r_id;
				if (!empty(${'response_'.$r_id.'_img'})) {
					unlink('..'.$response_img_dir.${'response_'.$r_id.'_img'});
				}
				continue;
			}
			// заполняем информацию по основным полям
			foreach ($field_kind as $fk) // имя, контакт, отзыв
				$out_file .= "\t".'$response_'.$r_id.'_'.$fk.' = "'
							.htmlspecialchars($_POST['response_'.$r_id.'_'.$fk]).'";'."\n";
			// картинка
			if (!empty($_FILES['response_'.$r_id.'_img']['name'])) {
				if ($_FILES['response_'.$r_id.'_img']['error'] === 0) {
					$handle = new upload($_FILES['response_'.$r_id.'_img']);
					if ($handle->uploaded) {
						$handle->file_new_name_body  	= 'response_'.$r_id;
						$handle->image_resize         	= true;
						$handle->image_x              	= 400;
						$handle->image_y        		= 345;
						$handle->image_ratio			= true;
						$handle->file_overwrite			= true;
						$handle->auto_create_dir		= true;
						$handle->process('..'.$response_img_dir);
						if ($handle->processed) {
							$out_file .= "\t".'$response_'.$r_id.'_img = "response_'.$r_id.'.'.$handle->file_dst_name_ext.'";'."\n";
							$handle->clean();
						} else {
							echo 'error : ' . $handle->error;
						}
					}
				}
			} else {
				$out_file .= "\t".'$response_'.$r_id.'_img = "'.$_POST['response_'.$r_id.'_cur_img'].'";'."\n";
			}
			$out_file .= "\t".'$response_'.$r_id.'_pos = "'.$resp_order[$r_id].'";'."\n";
			$out_file .= "\n";
		}
		// сохраняем обновленный список id-шников
		$res_resp_ids = implode(",",array_diff($resp_ids,$resp2delete));
		if (file_exists('../user/counter_rsp.php'))
			rename('../user/counter_rsp.php','../user/backups/bak_counter_rsp_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию counter_rsp.php!');
		file_put_contents('../user/counter_rsp.php','<? $resp_ids_string="'.$res_resp_ids.'"; ?>');

		// сохраняем сами отзывы
		$out_file = "<?\n" . $out_file . "?>";
		if (file_exists('../user/response.php'))
			rename('../user/response.php','../user/backups/bak_response_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию response.php!');
		file_put_contents('../user/response.php',$out_file);
	}

	$mnemonics = array('#RESP_ID#');
	$response_template = '	<tr id="#RESP_ID#" class="id">
		<td class="del_item_row"><a class="small_button" onclick="del_item(#RESP_ID#)"><span>del</span></a></td>
		<td class="dragHandle"></td>
		<td class="value">
			<table class="response">
				<tr>
					<td>Имя</td>
					<td><input name="response_#RESP_ID#_name" type="text" value="<?=${"response_#RESP_ID#_name"}?>"></td>
					<td rowspan="4">
						<img src="<?=$response_img_dir.${"response_#RESP_ID#_img"}?>" height="160px;" alt="" border="0">
						<input name="response_#RESP_ID#_cur_img" type="hidden" value="<?=${"response_#RESP_ID#_img"}?>">
					</td>
				</tr>
				<tr>
					<td>Контактная информация&nbsp;</td>
					<td><input name="response_#RESP_ID#_contact" type="text" value="<?=${"response_#RESP_ID#_contact"}?>"></td>
				</tr>
				<tr>
					<td>Отзыв</td>
					<td>
						<textarea name="response_#RESP_ID#_text" wrap="soft"><?=${"response_#RESP_ID#_text"}?></textarea>
					</td>
				</tr>
				<tr>
					<td>Файл картинки</td>
					<td><input name="response_#RESP_ID#_img" type="file" value=""></td>
				</tr>
			</table>
		</td>
		<td class="foto"></td>
	</tr>';


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"[]>
<html lang="ru-RU">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Редактирование отзывов</title>
    <link rel="stylesheet" href="/core/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/adm/adm_style.css" type="text/css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" href="/core/style.ie6.css" type="text/css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" href="/core/style.ie7.css" type="text/css" media="screen" /><![endif]-->
	<script type="text/javascript" src="/core/jquery.js"></script>
	<script type="text/javascript" src="/core/jquery.tablednd_0_5.js"></script>
	<script>
		$(document).ready(function() {
			$("#item_id").tableDnD({
				dragHandle: "dragHandle"
			});

			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});
		});

		function add_item() {
			var new_id = $('#last_id').val()*1 + 1;
			$('#last_id').val(new_id);
//			var tmp = document.getElementById('item_id').getElementsByTagName('TBODY')[0].innerHTML;
			$('#item_id_body').append('<?=preg_replace("/\<\?((?!\?\>).)*\?\>/","",str_replace(array("\r","\n"),"",$response_template))?>'.replace(/#RESP_ID#/g,new_id));
			$("#item_id").tableDnDUpdate();
			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});
			$("input[name='response_"+new_id+"_name']").focus();
		}

		function del_item(item_id) {
			if (confirm('Вы действительно хотите удалить отзыв от "'
				+$("input[name='response_"+item_id+"_name']").val()+'"?')) {
					$("#"+item_id).remove()
			}
		}
	</script>
</head>

<body style="min-width:500px;">
<?php
	include ('../user/response.php');
?>
<div id="make_response">
<form name="response_form" enctype="multipart/form-data" action="make_response.php" method="post"
	onsubmit="document.getElementById('item_id_order').value = $('#item_id').tableDnDSerialize();">
<input name="item_id_order" id="item_id_order" type="hidden" value="">
<span class="cfg_section_name">Отзывы</span>
<a class="button" href="#" onclick="$('form[name=response_form]').submit();"><span>Сохранить</span></a><br /><br /><br />
<table class="adm_table" id="item_id"><tbody id="item_id_body">
<?
	include ('../user/counter_rsp.php');
	$resp_ids = explode(",",$resp_ids_string);

	$resp2show = array();
	foreach ($resp_ids as $resp_id) $resp2show[${"response_".$resp_id."_pos"}] = $resp_id;
	$resp_max_id = $resp_id;
	if (!empty($resp2show)) {
		ksort($resp2show,SORT_NUMERIC);
		foreach ($resp2show as $resp_id) {
			$cur_template = $response_template;
			foreach ($mnemonics as $mnem) {
				$cur_template = str_replace($mnem,${strtolower(substr($mnem,1,-1))},$cur_template);
			}
			eval ('?>'.$cur_template.'<?');
		}
	}
?>
</tbody>
</table>
<input id="last_id" type="hidden" value="<?=$resp_max_id?>">
<br /><br /><a class="button" href="#" onclick="$('form[name=response_form]').submit();"><span>Сохранить</span></a>&nbsp;&nbsp;&nbsp;
<a class="button" onclick="add_item()"><span>Добавить</span></a>
</form>
</div>
</body>

</html>